

import java.io.IOException;

/**
 * @author Tzafrir
 *
 */
public class Log {

	private static TextFileHandler log;

	public static void init()
	{
		log= new TextFileHandler("log.txt",true);
		if (log.length()>10485760)
			logDelete();
		try {
			log.write("--------------------------------------------------------------------");
			log.write("Created at: "+ DateUtils.now("yyyy-MM-dd HH:mm:ss:SSS"));
			log.write("--------------------------------------------------------------------");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void logDelete()
	{
		log= new TextFileHandler("log.txt",false);
	}
	
	/**
	 * @param type - type of log file, taken from LogType enum
	 * @param msg - the meesage to be printed
	 */
	public static void write(LogType type, String msg)
	{
		if (msg==null)
		{
			Log.write(LogType.ERROR,"A null string was sent to log file");
			return;
		}
		msg=DateUtils.now("HH:mm:ss:SSS")+" "+msg;
		try
		{
			switch (type)
			{
				case SYSTEM:
					log.write("SYSTEM> "+msg);
					break;		
				case DEBUG:
					log.write("DEBUG>  "+msg);
					break;
				case ERROR:
					log.write("ERROR>  "+msg);
					break;
				case CONSOLE:
					System.out.println(msg);
					break;
			}
		}catch (IOException ex)
		{
			ex.printStackTrace();
		}
	}
	/**
	 * @param msg - String to write
	 */
	public static void error(String msg)
	{
		Log.write(LogType.ERROR, msg);
	}
	
	public static void debug(String msg)
	{
		Log.write(LogType.DEBUG, msg);
	}
	
	public static void system(String msg)
	{
		Log.write(LogType.SYSTEM, msg);
	}
	public static void console(String msg)
	{
		Log.write(LogType.CONSOLE, msg);
	}

	public static void writeEx(Exception ex)
	{
		Log.write(LogType.ERROR,ex.getMessage());
		ex.printStackTrace(log.getPrintWriter());
		ex.printStackTrace();
	}
}
